<template>
  <BasicModal
    width="100%"
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    :footer="null"
    :maskClosable="false"
  >
    <Button type="primary" @click="createApiHandle">
      <template #icon><PlusOutlined /></template>
      新建
    </Button>
    <Table
      style="margin-top: 8px"
      :columns="apiColumns"
      :data-source="apiListData"
      :pagination="false"
      bordered
    >
      <template #bodyCell="{ column, text, record, index }">
        <template v-if="column.dataIndex === 'serialNumber'">
          <div>
            <span> {{ index + 1 }}</span>
          </div>
        </template>
        <template
          v-else-if="
            ['apiTitle', 'apiCode', 'apiHttpMethod', 'apiUrl', 'apiParam', 'sort'].includes(
              column.dataIndex,
            )
          "
        >
          <div>
            <a-input
              v-if="editableData[record.id]"
              v-model:value="editableData[record.id][column.dataIndex]"
              style="margin: -5px 0"
            />
            <template v-else>
              <Tooltip :title="text">{{ text }}</Tooltip>
            </template>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'operation'">
          <div class="editable-row-operations">
            <span v-if="editableData[record.id]">
              <Popconfirm title="确认保存?" @confirm="saveApiHandle(record.id)">
                <a>保存</a>
              </Popconfirm>
              <a style="margin-left: 8px" @click="cancelApiHandle(record.id)">取消</a>
            </span>
            <span v-else>
              <a @click="editApiHandle(record.id)">编辑</a>
              <Popconfirm title="确认删除?" @confirm="removeApiHandle(record.id)">
                <a style="margin-left: 8px">删除</a>
              </Popconfirm>
            </span>
          </div>
        </template>
      </template>
    </Table>
  </BasicModal>
</template>
<script lang="ts">
  import { computed, defineComponent, reactive, ref, unref, UnwrapRef } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { Popconfirm, Table, Tooltip } from 'ant-design-vue';
  import { createApi, queryApiListByMenuId, modifyApi, removeApiById } from '/@/api/system/system';
  import { cloneDeep } from 'lodash-es';
  import { Button } from '/@/components/Button';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ApiReq, ApiResp } from '/@/api/system/modal/apiModel';
  import { apiColumns } from './menu.data';

  export default defineComponent({
    name: 'MenuApiModal',
    components: {
      Button,
      Tooltip,
      PlusOutlined,
      Table,
      Popconfirm,
      BasicModal,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();

      const isUpdate = ref(true);
      const id = ref('');
      const loading = ref(false);

      const apiListData = ref<ApiResp[]>([]);

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        id.value = data?.record?.id;

        await getListData();
      });

      const getTitle = computed(() => '菜单接口');

      const editableData: UnwrapRef<Record<string, ApiResp>> = reactive({});

      const getListData = async () => {
        const apiReq: ApiReq = {
          menuId: unref(id),
        };
        apiListData.value = await queryApiListByMenuId(apiReq);
      };
      const createApiHandle = () => {
        const id = 'TmpKey';
        const apiResp: ApiResp = {
          id: id,
        };
        apiListData.value.push(apiResp);
        editApiHandle(id);
      };

      const editApiHandle = (key: string) => {
        editableData[key] = cloneDeep(apiListData.value.filter((item) => key === item.id)[0]);
      };

      const saveApiHandle = async (key: string) => {
        try {
          Object.assign(apiListData.value.filter((item) => key === item.id)[0], editableData[key]);

          const apiReq: ApiReq = editableData[key];
          apiReq.menuId = unref(id);
          if (key === 'TmpKey') {
            apiReq.id = undefined;
            await createApi(apiReq);
          } else {
            await modifyApi(apiReq);
          }

          delete editableData[key];

          await getListData();
        } catch (error: any) {
          const { response, message } = error || {};
          const msg: string = response?.data?.message ?? message;
          createMessage.error(msg);
        }
      };

      const cancelApiHandle = (key: string) => {
        delete editableData[key];
      };

      const removeApiHandle = async (key: string) => {
        try {
          const ApiReq: ApiReq = {
            id: key,
          };
          await removeApiById(ApiReq);
        } catch (error: any) {
          const { response, message } = error || {};
          const msg: string = response?.data?.message ?? message;
          createMessage.error(msg);
        }
        await getListData();
      };

      async function handleSubmit() {
        try {
          closeModal();
          emit('success', {
            isUpdate: unref(isUpdate),
            values: {},
          });
        } catch (error: any) {
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        apiColumns,
        roleId: id,
        registerModal,
        getTitle,
        loading,
        apiListData,
        editableData,
        createApiHandle,
        editApiHandle,
        saveApiHandle,
        cancelApiHandle,
        removeApiHandle,
        handleSubmit,
      };
    },
  });
</script>
<style lang="less" scoped>
  ::-webkit-scrollbar {
    width: 3px;
    height: 6px;
  }

  ::-webkit-scrollbar-track-piece {
    background-color: rgba(0, 0, 0, 0.2);
    -webkit-border-radius: 6px;
  }

  ::-webkit-scrollbar-thumb:vertical {
    height: 3px;
    background-color: rgba(125, 125, 125, 0.7);
    -webkit-border-radius: 6px;
  }

  ::-webkit-scrollbar-thumb:horizontal {
    width: 3px;
    background-color: rgba(125, 125, 125, 0.7);
    -webkit-border-radius: 6px;
  }
</style>
